<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/* ****************************************************************************
  NAIYUMIE KING WANG JJANG Front End Developer <naiyumie@gmail.com>
  FileType:CRLF, Encording:UTF-8, Tab&Space:4/4
  ------------------------------------------------------------------------
  url 암호화를 위한 간략 암호화 라이브러리
**************************************************************************** */

class Nurl {
	private $CI;
	private $key;
	public function __construct() {
		$this -> CI = &get_instance();
		$this->key = "basically secret_nurl_key";
	}


	/***************************************************
	 * 암호화 복호화 type1
	 ***************************************************/
	function encrypt($string) {
		$key = $this->key;
		$result = '';
		$test = "";
		for($i=0; $i<strlen($string); $i++) {
			$char = substr($string, $i, 1);
			$keychar = substr($key, ($i % strlen($key))-1, 1);
			$char = chr(ord($char)+ord($keychar));
			$test[$char]= ord($char)+ord($keychar);
			$result.=$char;
		}
		return str_replace('%', '_', urlencode(base64_encode($result)));
	}

	function decrypt($string) {
		$key = $this->key;
		$result = '';
		$string = base64_decode(urldecode(str_replace('_', '%', $string)));
		for($i=0; $i<strlen($string); $i++) {
			$char = substr($string, $i, 1);
			$keychar = substr($key, ($i % strlen($key))-1, 1);
			$char = chr(ord($char)-ord($keychar));
			$result.=$char;
		}
		return $result;
	}


	/***************************************************
	 * 암호화 복호화 type2
	 ***************************************************/
	public function enc($msg) {
		$msg_len = strlen($msg);
		$string='';
		$buffer='';
		$key2='';
		$key = $this->key;
		while($msg) {
			$key2=pack('H*',md5($key.$key2.$buffer));
			$buffer=substr($msg,0,16);
			$enc_limit=strlen($buffer);
			$string.=$this->_bytexor($buffer,$key2,$enc_limit);
			$msg=substr($msg,16);
		}
		//$retVal = $string;
		$retVal = urlencode($string);
		return($retVal);
	}



	public function dec($msgarg) {
		$string='';
		$buffer='';
		$key2='';
		$key = $this->key;
		$msg = urldecode($msgarg);
		while($msg) {
			$key2=pack('H*',md5($key.$key2.$buffer));
			$dec_limit=strlen(substr($msg,0,16));
			$buffer=$this->_bytexor(substr($msg,0,16),$key2,$dec_limit);
			$string.=$buffer;
			$msg=substr($msg,16);
		}
		//$retVal = $string;
		$retVal = $string;
		return($retVal);
	}

	protected function _bytexor($a,$b,$ilimit) {
		$c='';
		for($i=0;$i<$ilimit;$i++) {
			$c .= $a{$i}^$b{$i};
		}
		return $c;
	}

}